import { parseArgs } from 'node:util';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
import esbuild from 'esbuild';

/**
 * 解析命令行参数
 */
const {
  values: { format },
  positionals,
} = parseArgs({
  allowPositionals: true,
  options: {
    format: {
      type: 'string',
      short: 'f',
      default: 'esm',
    },
  },
});

// 创建 esm 的 __filename
const __filename = fileURLToPath(import.meta.url);
// 创建 esm 的 __dirname
const __dirname = path.dirname(__filename);
const require = createRequire(import.meta.url);

const target = positionals.length ? positionals[0] : 'vue';
const entry = path.resolve(__dirname, `../packages/${target}/src/index.ts`);

const outfile = path.resolve(
  __dirname,
  `../packages/${target}/dist/${target}.${format}.js`
);
const pkg = require(`../packages/${target}/package.json`);

const ctx = await esbuild.context({
  entryPoints: [entry], // 入口文件
  outfile, // 输出文件
  format: format as esbuild.Format, // 打包格式 cjs, esm, iife
  platform: format === 'cjs' ? 'node' : 'browser', // 打包平台 node browser
  sourcemap: true, // 开启 sourcemap, 方便调试
  bundle: true, // 把所有的依赖打包到一个文件里面
  globalName: pkg.buildOptions.name,
});
ctx.watch();
